
#include "hex_util.h"
#include <stdbool.h>
#include <stdio.h>

// 判断给定字符串是否为16进制数
int str_is_hex(const char *value, uint32_t len) {
    int i = 0;
    while(i < len) {
        if (i == 0 && len >= 2 && value[0] == '0' && (value[1] == 'x' || value[1] == 'X')) {
            i += 2;
            continue;
        }
        if ((value[i] >= '0' && value[i] <= '9') || (value[i] >= 'a' && value[i] <= 'f') || (value[i] >= 'A' && value[i] <= 'F')) {
            i++;
            continue;
        }
        return false;
    }   
    return true;
}

// 将字节数组转换为十六进制字符数组
int encode_hex(const uint8_t *value, uint32_t len, char *buf, uint32_t *buf_len, int to_lower_case){
    int i = 0;
    int j = 0;
    int k = 0;
    int l = 0;
    if (buf == NULL || buf_len == NULL) {
        return -1;
    }
    if (*buf_len < 2 * len) {
        return -2;
    }
    *buf_len = 2 * len;
    for(i = 0; i < len; i++) {
        buf[k++] = to_lower_case ? "0123456789abcdef"[value[i] >> 4] : "0123456789ABCDEF"[value[i] >> 4];
        buf[k++] = to_lower_case ? "0123456789abcdef"[value[i] & 0x0f] : "0123456789ABCDEF"[value[i] & 0x0f];
    }
    return 0;
}

// 将十六进制字符数组转换为字节数组
int decode_hex(const char *value, uint32_t len, uint8_t *buf, uint32_t *buf_len) {
    int i = 0;
    int j = 0;
    int k = 0;
    int l = 0;
    char c1 = 0;
    char c2 = 0;
    if (buf == NULL || buf_len == NULL) {
        return -1;
    }
    if (*buf_len < len / 2 || len % 2 != 0) {
        return -2;
    }
    *buf_len = len / 2;
    for(i = 0; i < len / 2; i++) {
        c1 =  value[k];
        c2 =  value[k + 1];

        if (c1 >= '0' && c1 <= '9') {
            c1 = (c1 - '0');
        } else if (c1 >= 'a' && c1 <= 'f') {
            c1 = (c1 - 'a' + 10);
        } else if (c1 >= 'A' && c1 <= 'F') {
            c1 = (c1 - 'A' + 10);
        } else {
            return -3;
        }
        if (c2 >= '0' && c2 <= '9') {
            c2 = (c2 - '0');
        } else if (c2 >= 'a' && c2 <= 'f') {
            c2 = (c2 - 'a' + 10);
        } else if (c2 >= 'A' && c2 <= 'F') {
            c2 = (c2 - 'A' + 10);
        } else {
            return -3;
        }
        buf[i] = c1 << 4;
        buf[i] |= c2;
        k += 2;
    }
    return 0;
}